package com.zq.it.cms.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.Yaml;

import com.zq.it.cms.common.util.CommUtil;

public class MenuHolder implements InitializingBean{

	@Autowired
	private ApplicationContext context;
	@javax.annotation.Resource(name = "properties")
	private Properties properties;
	
	private TreeSet<Menu> menus;
	
	private boolean debug = false;

	private void initMenus() throws IOException{
		Resource[] resources = context.getResources("classpath:conf/**/menu*.yml");
		TreeSet<Menu> menus = new TreeSet<Menu>();
		for (Resource resource : resources) {
			Yaml yaml = new Yaml();
			InputStream is = resource.getInputStream();
			Map<Object, Map<Object, Object>> map = (Map<Object, Map<Object, Object>>) yaml.load(is);
			for (Map.Entry<Object, Map<Object, Object>> entry : map.entrySet()) {
				menus.add(Menu.parse(entry.getKey(), entry.getValue()));
			}
		}
		this.menus = Menu.sort(menus);
	}
	
	public TreeSet<Menu> getMenus(){
		if(debug){
			try {
				initMenus();
			} catch (Exception e) {
			}
		}
		return menus;
	}

	public void afterPropertiesSet() throws Exception {
		debug = CommUtil.toBoolean(properties.getProperty("menu.debug"));
		if(!debug){
			initMenus();
		}
	}
}
